﻿using System;
using System.Collections.Generic;
using Autodesk.Revit.Attributes;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;

namespace YRevitJig
{
	[Transaction(TransactionMode.Manual)]
	[Regeneration(RegenerationOption.Manual)]
	public class JigTexts : IExternalCommand
	{
		public Result Execute(ExternalCommandData cmdData, ref string message, ElementSet elements)
		{
			UIDocument activeUIDocument = cmdData.Application.ActiveUIDocument;
			ViewAssist.ViewValidating(activeUIDocument.Document, activeUIDocument.ActiveView);
			XYZ xyz = null;
			List<TextNote> list = new List<TextNote>();
			List<XYZ> list2 = new List<XYZ>();
			try
			{
				IList<Reference> list3 = activeUIDocument.Selection.PickObjects(Autodesk.Revit.UI.Selection.ObjectType.Element);
				foreach (Reference reference in list3)
				{
					TextNote textNote = activeUIDocument.Document.GetElement(reference) as TextNote;
					if (textNote != null)
					{
						BoundingBoxXYZ boundingBoxXYZ = textNote.get_BoundingBox(activeUIDocument.ActiveView);
						XYZ item = boundingBoxXYZ.Min + (boundingBoxXYZ.Max - boundingBoxXYZ.Min) / 2.0;
						list.Add(textNote);
						list2.Add(item);
					}
				}
				xyz = activeUIDocument.Selection.PickPoint("请选择基点<退出>:");
			}
			catch
			{
				return Autodesk.Revit.UI.Result.Succeeded;
			}
			XTextsJig xtextsJig = new XTextsJig(activeUIDocument);
			XYZ xyz2 = xtextsJig.DragTexts(list, list2, xyz, "请确定位置：");
			Result result;
			if (xyz2 == null)
			{
				xtextsJig.Dispose();
				result = Autodesk.Revit.UI.Result.Succeeded;
			}
			else
			{
				Transform transform = Transform.CreateTranslation(xyz2 - xyz);
				Transaction transaction = new Transaction(activeUIDocument.Document);
				transaction.Start("CreateText");
				foreach (TextNote textNote2 in list)
				{
					XYZ xyz3 = transform.OfPoint(textNote2.Coord);
					TextNote textNote3 = TextNote.Create(activeUIDocument.Document, activeUIDocument.ActiveView.Id, xyz3, textNote2.Text, textNote2.TextNoteType.Id);
				}
				transaction.Commit();
				xtextsJig.Dispose();
				result = Autodesk.Revit.UI.Result.Succeeded;
			}
			return result;
		}
	}
}
